use chrono::{Datelike, Local, Weekday};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::{
    menu::{Menu, MenuItem},
    tray::{MouseButton, TrayIconBuilder, TrayIconEvent},
    Manager, Runtime,
};
use tauri_plugin_clipboard_manager::ClipboardExt;

static TRAY_CREATED: AtomicBool = AtomicBool::new(false);

#[derive(Debug, Serialize, Deserialize)]
struct ReminderSettings {
    time: String,
    days: Vec<u32>,
    enabled: bool,
}

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn get_current_date() -> String {
    let now = Local::now();
    let weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    let weekday = weekdays[now.weekday().num_days_from_sunday() as usize];
    format!(
        "{}年{}月{}日 {}",
        now.year(),
        now.month(),
        now.day(),
        weekday
    )
}

#[tauri::command]
fn is_saturday() -> bool {
    Local::now().weekday() == Weekday::Sat
}

#[tauri::command]
fn get_next_monday() -> String {
    let today = Local::now();
    let days_until_monday = (7 - today.weekday().num_days_from_monday()) % 7;
    let next_monday = if days_until_monday == 0 {
        today + chrono::Duration::days(7)
    } else {
        today + chrono::Duration::days(days_until_monday as i64)
    };
    next_monday.format("%Y-%m-%d").to_string()
}

#[tauri::command]
async fn copy_to_clipboard(app: tauri::AppHandle, text: String) -> Result<(), String> {
    app.clipboard().write_text(text).map_err(|e| e.to_string())
}

#[tauri::command]
async fn show_notification(_title: String, _body: String) -> Result<(), String> {
    // 这里会在前端处理通知
    Ok(())
}

// 系统托盘功能
fn create_tray<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<()> {
    // 检查是否已经创建过托盘
    if TRAY_CREATED
        .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
        .is_err()
    {
        println!("托盘已存在，跳过创建");
        return Ok(());
    }

    let quit_i = MenuItem::with_id(app, "quit", "退出程序", true, None::<&str>)?;
    let show_i = MenuItem::with_id(app, "show", "显示窗口", true, None::<&str>)?;
    let hide_i = MenuItem::with_id(app, "hide", "隐藏窗口", true, None::<&str>)?;
    let menu = Menu::with_items(app, &[&show_i, &hide_i, &quit_i])?;

    let tray_id = format!("rbao_tray_{}", std::process::id());
    println!("创建托盘图标，ID: {}", tray_id);
    let _tray = TrayIconBuilder::with_id(&tray_id)
        .icon(app.default_window_icon().unwrap().clone())
        .menu(&menu)
        .tooltip("桌面日报应用")
        .show_menu_on_left_click(false)
        .on_menu_event(move |app, event| match event.id.as_ref() {
            "quit" => {
                // 先清理托盘图标，再退出应用
                cleanup_tray();
                app.exit(0);
            }
            "show" => {
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.set_focus();
                    let _ = window.unminimize();
                }
            }
            "hide" => {
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.hide();
                }
            }
            _ => {}
        })
        .on_tray_icon_event(|tray, event| {
            if let TrayIconEvent::Click {
                button: MouseButton::Left,
                button_state: _,
                ..
            } = event
            {
                let app = tray.app_handle();
                if let Some(window) = app.get_webview_window("main") {
                    if window.is_visible().unwrap_or(false) {
                        let _ = window.hide();
                    } else {
                        let _ = window.show();
                        let _ = window.set_focus();
                        let _ = window.unminimize();
                    }
                }
            }
        })
        .build(app)?;

    Ok(())
}

// 清理托盘图标
fn cleanup_tray() {
    println!("清理托盘图标");
    // 重置创建标志，允许重新创建
    TRAY_CREATED.store(false, Ordering::SeqCst);
}

#[tauri::command]
async fn enable_autostart() -> Result<(), String> {
    // 启用开机启动的逻辑
    Ok(())
}

#[tauri::command]
async fn disable_autostart() -> Result<(), String> {
    // 禁用开机启动的逻辑
    Ok(())
}

#[tauri::command]
fn should_convert_to_weekly() -> bool {
    // 检查是否应该转换为周计划
    // 周六或周日都可以转换
    let today = Local::now().weekday();
    today == Weekday::Sat || today == Weekday::Sun
}

#[tauri::command]
fn get_week_range() -> String {
    let today = Local::now();
    let days_until_monday = (7 - today.weekday().num_days_from_monday()) % 7;
    let next_monday = if days_until_monday == 0 {
        today + chrono::Duration::days(7)
    } else {
        today + chrono::Duration::days(days_until_monday as i64)
    };
    let next_friday = next_monday + chrono::Duration::days(4);

    format!(
        "{} - {}",
        next_monday.format("%m月%d日"),
        next_friday.format("%m月%d日")
    )
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    println!("开始启动Tauri应用...");
    tauri::Builder::default()
        .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
            println!("检测到第二个实例启动，聚焦现有窗口");
            // 当检测到第二个实例启动时，显示并聚焦现有窗口
            if let Some(window) = app.get_webview_window("main") {
                let _ = window.show();
                let _ = window.set_focus();
                let _ = window.unminimize();
            }
        }))
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_autostart::init(
            tauri_plugin_autostart::MacosLauncher::LaunchAgent,
            None,
        ))
        .plugin(tauri_plugin_clipboard_manager::init())
        .invoke_handler(tauri::generate_handler![
            get_current_date,
            is_saturday,
            get_next_monday,
            copy_to_clipboard,
            show_notification,
            enable_autostart,
            disable_autostart,
            should_convert_to_weekly,
            get_week_range
        ])
        .setup(|app| {
            println!("应用启动中...");
            // 创建系统托盘
            create_tray(app.handle())?;
            println!("托盘创建完成");

            // 设置窗口关闭事件处理
            let window = app.get_webview_window("main").unwrap();
            let window_clone = window.clone();
            window.on_window_event(move |event| {
                if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                    // 阻止默认关闭行为
                    api.prevent_close();
                    // 隐藏窗口而不是退出程序
                    let _ = window_clone.hide();
                }
            });

            // 注意：应用退出时的清理逻辑已在托盘菜单的quit事件中处理

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
